<template>
  <div class="NetworkDisk">
    <div class="but-div div-opacity">
      <!-- 顶部操作按钮 -->
      <el-button
        class="text"
        type="primary"
        icon="el-icon-upload"
        @click="showViewBut"
      >上传</el-button>
      <el-button
        class="but-er text"
        type="primary"
        icon="iconfont icon-xinjianwenjianjia"
        @click="newUpload"
      >新建文件夹</el-button>
      <div
        class="but-er sort cursor-p"
        @click="sortClick"
      >
        <i class="el-icon-sort"></i>
      </div>
      <el-input v-model="searchinput">
        <i
          slot="prefix"
          class="el-input__icon el-icon-search cursor-p"
          @click="selectSuo"
        ></i>
      </el-input>
    </div>
    <div
      class="nd-list div-opacity"
      v-loading.lock="vloading"
    >
      <div class="nb-l-readcrumb">
        <!-- 面包屑组件 -->
        <brea-dcrumb
          :listpro="listprol"
          :total="uplist.length"
          @popEmit="popemiton"
          @rootEmit="rootnull"
          @breadEmit="bread"
        ></brea-dcrumb>
      </div>
      <div class="list-item">
        <!-- 头部导航 -->
        <div class="li-it-div">
          <div class="li-it-checkbox">
            <label
              role="checkbox"
              class="label-cla"
            >
              <span
                class="icon-checkBox icon-checkBox-select"
                :class="{ 'icon-coloe': checkBox }"
                @click="checkBoxClick()"
              ></span>
              <input
                type="checkbox"
                name="cke1"
                class="ipt-chck"
                value="内容1"
              />
            </label>
          </div>
          <div
            class="li-it-title text-fonw"
            style="width: 39.7%"
          >文件名</div>
          <div class="li-it-date text-fonw">修改时间</div>
          <div class="li-it-sise text-fonw">大小</div>
          <div class="li-it-cao text-fonw">操作</div>
        </div>
        <div class="li-it-scroll">
          <!-- 新建文件夹 UI -->
          <div
            class="li-it-div liit-div-hover"
            v-if="isnewuplode"
          >
            <div class="li-it-checkbox">
              <label
                role="checkbox"
                class="label-cla"
              >
                <span class="icon-checkBox icon-checkBox-select"></span>
                <input
                  type="checkbox"
                  name="cke1"
                  class="ipt-chck"
                  value=""
                />
              </label>
            </div>
            <div class="li-it-title">
              <svg
                class="icon-symbol icon-svg-yasuobao"
                aria-hidden="true"
              >
                <use xlink:href="#icon-wenjianjia"></use>
              </svg>
              <el-input
                ref="liitelinput"
                class="li-it-elinput"
                v-model="newuplode.title"
              ></el-input>
              <i
                class="el-icon-success li-it-elinput-icon"
                @click="uploadSuccess"
              ></i>
              <i
                class="el-icon-error li-it-elinput-icon"
                @click="newUpload"
              ></i>
            </div>
            <div class="li-it-date item-date">
              {{ newuplode.text_date }}
            </div>
            <div class="li-it-sise item-date">-</div>
            <div class="li-it-cao">
              <i class="el-icon-share liit-icon"></i>
              <i class="el-icon-download liit-icon"></i>
              <i class="el-icon-more liit-icon"></i>
            </div>
          </div>
          <!-- 文件列表 -->
          <div
            class="li-it-div liit-div-hover"
            v-for="(item, index) in uplist"
            :key="index"
            @contextmenu.stop.prevent="lintextmenu(index,$event)"
          >
            <div class="li-it-checkbox">
              <label
                role="checkbox"
                class="label-cla"
              >
                <span
                  class="icon-checkBox icon-checkBox-select"
                  :class="{ 'icon-coloe': item.ischeckBox }"
                  @click="itemcheckBoxClick(index)"
                ></span>
                <input
                  type="checkbox"
                  name="cke1"
                  class="ipt-chck"
                  value=""
                />
              </label>
            </div>
            <div class="li-it-title">

              <img
                v-if="item.img"
                :src="item.img"
                class="solist-img"
              >
              <svg
                v-else
                class="icon-symbol icon-svg-yasuobao"
                aria-hidden="true"
              >
                <!-- <use v-bind:xlink:href="item.icon"></use> -->
                <use v-bind:xlink:href="item.icon"></use>
              </svg>
              <template v-if="item.istitle">
                <span
                  class="li-it-text liit-title"
                  @click="liitTitleClick(index)"
                >{{ item.title }}</span>
              </template>
              <template v-else>
                <el-input
                  ref="liitelinput"
                  class="li-it-elinput"
                  v-model="newuplode.title"
                ></el-input>
                <i
                  class="el-icon-success li-it-elinput-icon"
                  @click="uptitle(index)"
                ></i>
                <i
                  class="el-icon-error li-it-elinput-icon"
                  @click="newuptitle(index)"
                ></i>
              </template>
            </div>
            <div class="li-it-date item-date">
              {{ item.update_date }}
            </div>
            <div class="li-it-sise item-date">
              {{ item.size }}
            </div>
            <div
              class="li-it-cao"
              v-if="item.size != '-' "
            >
              <i
                class="el-icon-share liit-icon"
                @click="shareClick(index)"
              ></i>
              <i
                class="el-icon-download liit-icon"
                @click="download(index)"
              ></i>
              <i
                class="el-icon-more liit-icon"
                @click="lintextmenu(index,$event)"
              ></i>
            </div>
          </div>
        </div>
      </div>
    </div>
    <upload-sidebar ref="uploadsidebar"></upload-sidebar>
    <upload-list
      ref="uploadlist"
      @uploadHttpEmit='uphttp'
    ></upload-list>
    <con-text-menu
      :pleft='context.left'
      :ptop='context.top'
      :prindex='checkBoxindex'
      :prchckxList='ischeckBoxList'
      @indexhide='onindexhide'
      @dakaiEmit='liitTitleClick'
      @fenXiangEmit='shareClick'
      @xiazai='download'
      @rename='onrename'
      @yidong='onyidong'
      @updel='onupdel'
      ref="ConTextMenu"
    ></con-text-menu>
    <sh-aer ref="shaer"></sh-aer>
    <move-file
      :procheckBoxList='ischeckBoxList'
      ref="movefile"
      @movesuccess='onmovesuccess'
    ></move-file>
  </div>
</template>

<script>
import { dateNew, MapList, sizeZhuanHuan } from '@/common/utils'
import BreaDcrumb from '@/components/Upload/BreaDcrumb.vue'
import ConTextMenu from '@/components/Upload/ConTextMenu.vue'
import UploadSidebar from '@/components/Upload/UploadSidebar.vue'
import UploadList from '@/components/Upload/UploadList.vue'
const shAer = () => import('@/components/Upload/share.vue')
const MoveFile = () => import('@/components/Upload/MoveFile.vue')
import httpurl from '@/common/API/http-config/config'
// 异步加载组件
// const UploadSidebar = () => import('@/components/UploadSidebar/UploadSidebar.vue')
// const UploadList = () => import('@/components/UploadList/UploadList.vue')
let upPath = {}
// let puPathList = []
export default {
  name: 'NetworkDisk',
  components: {
    BreaDcrumb,
    UploadSidebar,
    UploadList,
    ConTextMenu,
    shAer,
    MoveFile,
  },
  data() {
    return {
      // loading加载
      vloading: false,
      // 新建文件夹
      isnewuplode: false,
      // 新建文件object
      newuplode: {
        title: '',
        establish_date: null,
        text_date: '',
      },
      // 搜索input
      searchinput: '',
      // 面包屑组件
      listprol: [],
      // 全选按钮
      checkBox: false,
      // 列表组件
      uplist: [],
      context: {
        left: 0,
        top: 0,
      },
      checkBoxindex: null,
      // 按钮选中
      ischeckBoxList: [],
    }
  },
  created() {
    this.getDateList()
  },
  methods: {
    // 获取所有顶级的文件夹或文件
    async getDateList() {
      const request = await this.$http.host.get('/folder', { userid: this.$store.state.userinfo.id })
      const li = this.handleDate(request.data)
      this.uplist = li
    },
    // 处理列表数据
    handleDate(arr) {
      let list = arr
      list.forEach(item => {
        let date = dateNew(item.update_date)
        item.update_date = date.he
        item.icon = MapList.get(item.icon)
        item.img = item.icon == 2 ? httpurl.host + '/' + item.path : false
        item.size = item.size === null ? '-' : sizeZhuanHuan(item.size)
      })
      return list
    },
    // 自定义事件返回上一级
    popemiton(val) {
      this.listprol = val
      // puPathList.pop()
      this.$store.commit('hostmodeule/getbdl', { is: 3 })
      this.requestuplist()
      // if (this.listprol.length == 0) {
      //   this.getDateList()
      // } else {
      //   const bdl = this.$store.state.hostmodeule.breaDcrumbList
      //   const bdllength = this.$store.state.hostmodeule.breaDcrumbList.length
      //   this.lookup_Children(10, bdl[bdllength - 1].id)
      // }
    },
    // 点击全部文件回调
    rootnull() {
      this.listprol = []
      this.$store.commit('hostmodeule/getbdl', { is: 0, arr: [] })
      this.getDateList()
    },
    // 点击了某个级
    bread(val, index) {
      this.vloading = true
      if (val) {
        this.listprol = val
        // puPathList.splice(index)
        this.$store.commit('hostmodeule/getbdl', { is: 1, index })
        this.requestuplist()
        // if (this.listprol.length == 0) {
        //   this.getDateList()
        // } else {
        //   const bdl = this.$store.state.hostmodeule.breaDcrumbList
        //   this.lookup_Children(10, bdl[index - 1].id)
        // }
      } else {
        this.selectSuo()
      }
      this.vloading = false
    },
    // 按钮全选
    checkBoxClick() {
      this.checkBox = !this.checkBox
      let upda = this.uplist
      upda.forEach(item => {
        item.ischeckBox = this.checkBox
      })
      this.uplist = upda
      // 全选添加进
      if (this.checkBox) {
        this.ischeckBoxList = upda
      }
    },
    // 单个按钮选择
    itemcheckBoxClick(index) {
      const upi = this.uplist[index].ischeckBox
      this.uplist[index].ischeckBox = !upi
      // 判断按钮选中  ischeckBoxList数组存选中的按钮
      if (this.uplist[index].ischeckBox) {
        this.ischeckBoxList.push(this.uplist[index])
      } else {
        const indexid = this.ischeckBoxList.findIndex(item => (item.id = this.uplist[index].id))
        this.ischeckBoxList.splice(indexid, 1)
      }
    },
    // 文件名点击
    liitTitleClick(index) {
      if (this.uplist[index].path) return
      // 保存父级目录信息
      upPath = this.uplist[index]
      // puPathList.push(item)
      this.$store.commit('hostmodeule/getbdl', { is: 2, arr: this.uplist[index] })
      // 开启加载
      this.vloading = true
      // 面包屑组件 插入点击的文件夹
      this.listprol.push(this.uplist[index].title)
      this.lookup_Children(this.$store.state.userinfo.id, this.uplist[index].id)
      // 关闭加载
      this.vloading = false
    },
    // 请求子级目录文件
    async lookup_Children(userid, folderid) {
      const request = await this.$http.host.get('/lookup_Children', {
        userid: userid,
        folderid: folderid,
      })
      // 更新数据
      this.uplist = this.handleDate(request.data)
    },
    // 侧边选择文件
    showViewBut() {
      this.$refs.uploadsidebar.showView()
    },
    // 正在上传文件列表
    sortClick() {
      this.$refs.uploadlist.showView()
    },
    // 新建文件夹
    newUpload() {
      this.isnewuplode = !this.isnewuplode
      if (this.isnewuplode) {
        let date = new Date()
        // 保存时间戳
        this.newuplode.establish_date = (date.getTime() / 1000).toFixed()
        // 格式化时间戳
        date = dateNew(date.getTime())
        // 拼接时间戳
        this.newuplode.text_date = date.Y + '-' + date.m + '-' + date.m + '  ' + date.H + ':' + date.i
        // 宏异步调用focus事件  input获取焦点
        this.$nextTick(() => {
          this.$refs.liitelinput.focus()
        })
      } else {
        this.newuplode = {
          title: '',
          establish_date: null,
          text_date: '',
        }
      }
    },
    // 确认新建文件夹
    async uploadSuccess() {
      const _this = this
      // 查找父级目录id
      let parent_file_id = null
      // 判断有没有父级目录
      if (this.listprol.length == 0) {
        parent_file_id = 0
      } else {
        parent_file_id = upPath.id
      }
      try {
        // 发起请求前打开加载
        this.vloading = true
        const request = await this.$http.host.post('/addfolder', {
          establish_date: _this.newuplode.establish_date,
          icon: 0,
          ischeckBox: 0,
          parent_file_id,
          title: _this.newuplode.title,
          update_date: _this.newuplode.establish_date,
          userid: this.$store.state.userinfo.id,
        })
        // 判断添加成功
        if (request.code == 200) {
          this.requestuplist()
        } else {
          // 添加失败
          this.$message({
            type: 'error',
            message: request.msg,
          })
        }
      } catch (error) {
        console.error('新建文件夹请求错误', error)
      }
      // 关闭新建文件夹UI
      this.isnewuplode = false
      this.newuplode = {
        title: '',
        establish_date: null,
        text_date: '',
      }
      // 最后关闭加载
      this.vloading = false
    },
    // 列表鼠标右键点击
    lintextmenu(index, e) {
      let { x, y } = e
      this.context = {
        left: x,
        top: y,
      }
      // 判断按钮选中
      if (!this.uplist[index].ischeckBox) {
        this.itemcheckBoxClick(index)
      }
      this.checkBoxindex = index
    },
    // 刷新当前目录列表
    requestuplist() {
      if (this.listprol.length == 0) {
        this.getDateList()
      } else {
        const bdl = this.$store.state.hostmodeule.breaDcrumbList
        this.lookup_Children(10, bdl[bdl.length - 1].id)
      }
    },
    // 监听文件全部上传完成 刷新目录
    uphttp() {
      this.requestuplist()
      // 2.5秒后关闭上传列表
      setTimeout(() => {
        console.log('关闭上传列表')
        this.$refs.uploadlist.hideView()
        this.$refs.uploadlist.fileList = []
      }, 2500)
    },
    // 搜索回调
    async selectSuo() {
      if (this.searchinput == '') return
      const request = await this.$http.host.get('/selectFolderUpload', {
        userid: this.$store.state.userinfo.id,
        name: this.searchinput,
      })
      this.uplist = this.handleDate(request.data)
      // 重新搜索   清空面包屑组件中的数据Vuex中的目录记录数组
      if (this.listprol.length > 0) {
        this.listprol = []
        this.$store.commit('hostmodeule/getbdl', { is: 0, arr: [] })
      }
      this.listprol.push(`搜索:${this.searchinput}`)
    },
    // 右键菜单关闭   清空当前选中的按钮
    onindexhide(index) {
      this.itemcheckBoxClick(index)
      this.checkBoxindex = null
      this.ischeckBoxList = []
      this.uplist.forEach(item => {
        item.ischeckBox = false
      })
    },
    // icon分享点击
    shareClick(index) {
      const obj = this.uplist[index]
      this.$refs.shaer.hide(obj)
      // 判断是否右键下载 下载完成关闭按钮选中
      if (this.checkBoxindex) {
        this.onindexhide(index)
      }
    },
    // icon下载   使用a标签下载
    download(index) {
      this.$http.host
        .get(
          '/downloadUpload',
          {
            path: this.uplist[index].path,
            title: this.uplist[index].title,
            id: this.uplist[index].id,
          },
          {
            responseType: 'blob',
          }
        )
        .then(res => {
          var blob = new Blob([res.data])
          var downloadElement = document.createElement('a')
          var href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = this.uplist[index].title //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
      // 判断是否右键下载 下载完成关闭按钮选中
      if (this.checkBoxindex) {
        this.onindexhide(index)
      }
    },
    // 确然重命名
    async uptitle(index) {
      this.vloading = true
      // 判断是不是文件类型
      let uploadtype = 0
      if (this.uplist[index].path) {
        uploadtype = 1
      }
      try {
        const request = await this.$http.host.post('/rename', {
          title: this.newuplode.title,
          uploadname: this.uplist[index].uploadname,
          uploadtype,
          id: this.uplist[index].id,
          userid: this.$store.state.userinfo.id,
        })
        if (request.success == 1) {
          this.$message.success(request.msg)
          // 刷新目录
          await this.requestuplist()
        } else {
          this.$message.error(request.msg)
        }
      } catch (error) {
        this.$message.error('修改失败！')
      }
      // 关闭修改UI样式
      this.newuptitle(index)
      this.vloading = false
    },
    // 取消重命名
    newuptitle(index) {
      this.newuplode.title = ''
      this.uplist[index].istitle = true
      // 关闭按钮选中
      this.onindexhide(index)
    },
    // 重命名回调函数
    onrename(index) {
      const arr = this.uplist
      arr.forEach(item => {
        item.istitle = true
        item.ischeckBox = false
      })
      this.uplist = arr
      this.newuplode.title = this.uplist[index].title
      this.uplist[index].istitle = false
      this.uplist[index].ischeckBox = true
    },
    // 移动回调函数
    onyidong(index) {
      this.$refs.movefile.hideComponents()
      // 关闭按钮选中
      // this.onindexhide(index)
    },
    // 移动成功回调
    onmovesuccess() {
      // 直接刷新当前目录
      this.requestuplist()
    },
    // 删除回调函数
    onupdel() {
      this.$confirm('此操作将删除该文件, 是否继续?如要恢复请联系系统管理员', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.vloading = true
        let getdata = []
        this.ischeckBoxList.forEach(item => {
          if (item.path) {
            getdata.push({ id: item.id, biao: 1 })
          } else {
            getdata.push({ id: item.id, biao: 0 })
          }
        })
        try {
          const request = await this.$http.host.post('/delupload', { idlist: getdata })
          if (request.success == 1) {
            // 刷新目录
            await this.requestuplist()
          } else {
            this.$message.error(request.msg)
          }
        } catch (error) {
          this.$message.error('错误')
        }
        this.vloading = false
      })
    },
  },
  destroyed() {
    upPath = null
    // puPathList = null
  },
}
</script>

<style lang="scss" scoped>
$li-it-height: 53px;
.icon-symbol {
  width: 2.5em;
  height: 2.5em;
  vertical-align: 0;
  fill: currentColor;
  overflow: hidden;
}

.div-opacity {
  opacity: $opacit-y;
}

.NetworkDisk {
  width: 100%;
  height: 100%;

  .but-div {
    position: relative;
    height: 2.8rem;
    @include div-f-p;
    @include dif-alc;

    .but-er {
      background-color: #f0fbff;
      border-color: #f0fbff;
      color: #06a7ff;
      width: 150px;
    }

    .text {
      font-weight: 700;
    }

    .sort {
      text-align: center;
      height: 45px;
      font-size: 20px;
      margin: 0 10px;
      border-radius: 15px;

      .el-icon-sort {
        line-height: 45px;
      }
    }

    .el-icon-search {
      font-size: 22px;
    }
  }

  .nd-list {
    width: calc(100% - 20px);
    min-height: calc(100vh - 9.5rem - 20px);
    background-color: #fff;
    border-radius: 10px;
    padding: 10px;

    .nb-l-readcrumb {
      width: 100%;
    }
    .list-item {
      width: 100%;
      height: 100%;

      .li-it-div {
        width: 100%;
        height: $li-it-height;
        @include dif-alc;
        border-bottom: 1px solid #f9f9f9;
        font-size: 12px;

        .li-it-checkbox {
          width: 50px;
          height: 100%;
          margin-left: 20px;
          @include dif-alc;

          .label-cla {
            position: relative;
            vertical-align: middle;
          }

          .icon-checkBox {
            display: inline-block;
            width: 15px;
            height: 15px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            background-color: #fff;
            position: relative;
            vertical-align: middle;
          }
          .icon-checkBox::after {
            border: 2px solid rgb(255, 255, 255);
            border-left: 0;
            border-top: 0;
            content: '';
            top: 1px;
            left: 5px;
            position: absolute;
            width: 3px;
            height: 8px;
            -webkit-transform: rotate(45deg) scale(0);
            transform: rotate(45deg) scale(0);
            -webkit-transition: -webkit-transform 0.2s;
            transition: -webkit-transform 0.2s;
            transition: transform 0.2s;
            transition: transform 0.2s, -webkit-transform 0.2s;
          }
          .icon-checkBox-select::after {
            border-color: rgb(255, 255, 255);
            -webkit-transform: rotate(45deg) scale(1);
            transform: rotate(45deg) scale(1);
          }
          .ipt-chck {
            display: none;
          }
          .icon-coloe {
            background-color: #409eff;
            border-color: #409eff;
          }
        }

        .li-it-title {
          width: 39.8%;
          height: $li-it-height;
          line-height: 50px;
          @include dif-alc;

          .li-it-text {
            max-width: 350px;
            margin-left: 20px;
            @include text-d;
          }

          .liit-title {
            cursor: pointer;
          }

          .li-it-text:hover {
            color: #06a7ff;
          }

          .li-it-elinput {
            width: 220px;
          }

          .li-it-elinput ::v-deep .el-input__inner {
            width: 200px;
            height: 30px;
            margin-left: 20px;
          }

          .li-it-elinput-icon {
            font-size: 27px;
            margin-left: 5px;
            color: #06a7ff;
          }

          .solist-img {
            width: 30px;
            height: 30px;
            border-radius: 5px;
          }
        }

        .li-it-date {
          width: 20%;
          height: $li-it-height;
          line-height: 50px;
        }

        .item-date {
          color: #afb3bf;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
        }

        .li-it-sise {
          width: 20%;
          height: $li-it-height;
          line-height: 50px;
        }

        .li-it-cao {
          flex: 1;
          height: $li-it-height;
          line-height: 50px;
          @include dif-alc;
        }

        .liit-icon {
          font-size: 18px;
          margin-right: 20px;
        }

        .liit-icon:hover {
          color: #06a7ff;
          cursor: pointer;
        }

        .text-fonw {
          font-weight: 700;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
        }
      }

      .liit-div-hover:hover {
        background-color: #f5f5f594;
      }

      .li-it-scroll {
        width: 100%;
        height: calc(100vh - 16rem);
        @include scroll-scss;
        overflow-x: hidden;
      }

      .li-it-scroll::-webkit-scrollbar {
        @include scrollbar;
        background-color: #fff;
      }

      .li-it-scroll::-webkit-scrollbar-track {
        @include scrollbar-track;
      }

      .li-it-scroll::-webkit-scrollbar-thumb {
        @include scrollbar-thumb;
      }
    }
  }
}
.but-div ::v-deep .el-input {
  position: absolute;
  right: 30px;
  width: 300px;
}
.but-div ::v-deep .el-button--primary {
  width: 110px;
  border-radius: 15px;
}
.but-div ::v-deep .el-input__inner {
  border-radius: 25px;
}
</style>
